Javascript Variables


Published on: July 03, 2021 By T.Andrew Rayan

Javascript variables are used to hold values to it. It can store values of any type.

The name of the variable has to be clear and readable.

It can start with letters, underscore(_) or dollar($) symbol.

It should not start with numbers(0-9).

Example

var userName = "ReadersBuddy";

To create a variable we use the keyword var. Here we have created a variable with name userName and assigned a value ReadersBuddy to it. We have used camelCase syntax to the variable.

The variable that is declared inside the function is also accessible outside the function.

We shall see with an example

Output

30
20

Now we have a variable x with value 20 and inside the function the value of variable x is 10. When trying to print the value of x, it prints 20, since its declared outside and has global scope.

To avoid this availability of variable outside the function we can use the let keyword.

The let keyword will be available only within the scope of the block.

Example

Output

30
Uncaught ReferenceError: x is not defined

Here the variable x and y will not be available outside the function. This is the modern way to declare a variable.

We can also use const keyword to declare a variable. It is similar to the let keyword which will be available within the scope. The only difference is that the variable declared with const keyword will not be able to reassign with new value.

It will throw an error when we try to reassign any new value to the variable.

Example

Output

Uncaught TypeError: Assignment to constant variable.

We can use let keyword to declare a variable and const keyword to the variable which does not change and remains same throughout the program execution.


Most Read